package zhongbo.javaweb.instagram.util.sha1;

import zhongbo.javaweb.instagram.util.IoUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @see <a href="https://blog.csdn.net/baidu_32739019/article/details/93200066>SHA1加密算法（java实现）</a>
 * @since 2022-01-14 15:09
 */
public class SecuritySha1Utils {

    private static final String USE_CHARSET = "UTF-8";

    /**
     * SHA1实现
     *
     * @param inStr 输入文本
     * @return sha1后code
     * @throws Exception Exception
     * @author Ron
     * @since 2017年9月13日 下午3:30:36
     */
    public static String shaEncode(String inStr) throws Exception {
        byte[] byteArray = inStr.getBytes(USE_CHARSET);
        return shaEncode(byteArray);
    }

    /**
     * SHA1实现
     *
     * @param byteArray 输入字节数组
     * @return sha1后code
     * @author Ron
     * @since 2017年9月13日 下午3:30:36
     */
    public static String shaEncode(byte[] byteArray) {
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] md5Bytes = sha.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void main(String[] args) throws Exception {
        String str = "amigoxiexiexingxing";
        System.out.println("原始：" + str);
        System.out.println("SHA后：" + shaEncode(str));


        File file = new File("G:\\工作\\爬虫\\_temp\\_hash_pic\\46ec285c159c8cf592e80563a2670ce74deac1c0.jpg");


        str = "https://scontent-hkt1-1.cdninstagram.com/v/t51.2885-15/e15/271652802_945873886062529_2805155881285006017_n.jpg?_nc_ht=scontent-hkt1-1.cdninstagram.com&_nc_cat=101&_nc_ohc=zmAnbBDXPNgAX9I5x16&edm=APU89FABAAAA&ccb=7-4&oh=00_AT__aP3E0O2jHVzaJRnOauCkkeADz3gnR2hpelNa3m1-Ww&oe=61E72246&_nc_sid=86f79a";
        System.out.println("原始：" + str);
        System.out.println("SHA后：" + shaEncode(str));


        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = IoUtils.readFully(inputStream, -1, true);
        String sha1 = shaEncode(bytes);
        String fileHash = file.getName().replace(".jpg", "");
        boolean aCase = fileHash.equalsIgnoreCase(sha1);
        System.out.println("file hash  = " + fileHash + "  \nsha1       = " + sha1 + "  \n  equals   = " + aCase);
        System.out.println("sha1=" + sha1);
    }
}
